<script setup lang="ts">
import {
  getPatientListService,
  addPatientService,
  updatePatientService,
  deletePatientService,
} from '@/api/user'
import { computed, onMounted, ref, watch } from 'vue'
import type { Patient, PatientList } from '@/types/user'
import { Dialog, Toast } from 'vant'
import idValidator from 'id-validator'
import { useRoute, useRouter } from 'vue-router'
import { useConsultStore } from '@/stores'
// 患者信息列表
const patientList = ref<PatientList>([])
const getPatientList = async () => {
  try {
    const res = await getPatientListService()
    patientList.value = res
    // 设置默认选中的ID，当你是选择患者的时候，且有患者信息的时候
    if (isChange.value && patientList.value.length) {
      const defPatient = patientList.value.find((item) => item.defaultFlag === 1)
      if (defPatient) choosed.value = defPatient.id!
      else choosed.value = patientList.value[0].id!
    }
  } catch (error) {
    console.log(error)
  }
}
// 侧边栏是否显示
const show = ref(false)

// 性别
const options = [
  {
    label: '男',
    value: 1,
  },
  {
    label: '女',
    value: 0,
  },
]

const patientData = ref({
  id: '',
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0,
})
const defaultFlag = ref(false)

const savePatient = async () => {
  /**
   * 校验表单
   * 1. 姓名不能为空
   * 2. 身份证号不能为空
   */
  if (!patientData.value.name) {
    Toast.fail('请输入真实姓名')
    return
  }
  if (!patientData.value.idCard) {
    Toast.fail('请输入身份证号')
    return
  }
  // 校验身份证号
  const validator = new idValidator()
  if (!validator.isValid(patientData.value.idCard)) return Toast.fail('身份证格式不正确')
  // 校验性别
  const { sex } = validator.getInfo(patientData.value.idCard)
  if (patientData.value.gender !== sex) return Toast.fail('选择的性别和身份证上性别不一致')
  // 全部校验通过后 todo...
  try {
    patientData.value.defaultFlag = defaultFlag.value ? 1 : 0
    isEdit.value
      ? await updatePatientService(patientData.value)
      : await addPatientService({
          name: patientData.value.name,
          idCard: patientData.value.idCard,
          gender: patientData.value.gender,
          defaultFlag: patientData.value.defaultFlag,
        })
    Toast.success(isEdit.value ? '保存成功' : '添加成功')
    // 重新获取患者列表
    getPatientList()
    show.value = false // 关闭弹窗
  } catch (error) {
    console.log(error)
  }
}

// 编辑患者
const isEdit = ref(false)
const showEdit = (patient: Patient) => {
  isEdit.value = true
  patientData.value = {
    id: patient.id || '',
    name: patient.name,
    idCard: patient.idCard,
    gender: patient.gender,
    defaultFlag: patient.defaultFlag,
  }
  defaultFlag.value = patient.defaultFlag === 1
  show.value = true
}

// 删除患者
const deletePatient = async () => {
  try {
    await Dialog.confirm({
      title: '友情提示',
      message: '确定删除该患者吗？',
    })
    await deletePatientService(patientData.value.id)
    Toast.success('删除成功')
    getPatientList()
    show.value = false
  } catch (error) {
    console.log(error)
  }
}
// 监听弹窗显示状态做表单初始化
watch(show, (newVal) => {
  if (!newVal) {
    // 关闭弹窗时清空表单数据
    patientData.value = {
      id: '',
      name: '',
      idCard: '',
      gender: 1,
      defaultFlag: 0,
    }
    defaultFlag.value = false
    isEdit.value = false
  }
})

// 获取路由字符串参数
const route = useRoute()
const isChange = computed(() => {
  return route.query.isChange === '1'
})
const choosed = ref('')

// 下一步
const consultStore = useConsultStore()
const router = useRouter()
const next = () => {
  // 选择患者后,记录到store
  if (!choosed.value) return Toast('请选择问诊患者')
  consultStore.setPatient(choosed.value)
  // 跳转到下一个页面
  router.push('/consult/pay')
}
onMounted(() => {
  getPatientList()
})
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'" />
    <!-- 头部选择提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        v-for="patient in patientList"
        :key="patient.id"
        @click="choosed = <string>patient.id"
        :class="choosed === patient.id ? 'selected' : ''"
      >
        <div class="info">
          <span class="name">{{ patient.name }}</span>
          <span class="id">{{
            patient.idCard.replace(/^(.{6})(?:\d+)(.{4})$/, '\$1******\$2')
          }}</span>
          <span>{{ patient.genderValue }}</span>
          <span>{{ patient.age }}岁</span>
        </div>
        <div class="icon" @click="showEdit(patient)"><cp-icon name="user-edit" /></div>
        <div class="tag" v-if="patient.defaultFlag === 1">默认</div>
      </div>
      <div class="patient-add" v-if="patientList.length < 6" @click="show = true">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 患者选择下一步 -->
    <div class="patient-next" v-if="isChange">
      <van-action-bar>
        <van-action-bar-button type="danger" @click="next" text="下一步"></van-action-bar-button>
      </van-action-bar>
    </div>
    <!-- 新增患者弹层 -->
    <van-popup v-model:show="show" position="bottom">
      <!-- 新增患者导航栏 -->
      <cp-nav-bar
        :title="isEdit ? '编辑患者' : '添加患者'"
        right-text="保存"
        @click-right="savePatient"
        :back="() => (show = false)"
      ></cp-nav-bar>
      <!-- 表单 -->
      <van-form autocomplete="off" ref="formRef">
        <van-field label="真实姓名" placeholder="请输入真实姓名" v-model="patientData.name" />
        <van-field label="身份证号" placeholder="请输入身份证号" v-model="patientData.idCard" />
        <van-field label="性别">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn :options="options" v-model="patientData.gender"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <!-- 值为布尔类型 -->
            <van-checkbox round v-model="defaultFlag" />
          </template>
        </van-field>
      </van-form>
      <!-- 编辑状态下才显示删除按钮 -->
      <van-action-bar v-if="isEdit">
        <van-action-bar-button
          type="danger"
          text="删除"
          @click="deletePatient"
        ></van-action-bar-button>
        +
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  ::v-deep() {
    .van-popup {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      padding-top: 46px;
    }
  }
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: bold;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
</style>
